import 'dart:ui';
import 'package:flutter/material.dart';

/* 
  使用：
    child: RepaintBoundary(
      child: CustomPaint(
        painter: CNMDottedLinePainer(),
        child: SizedBox(
          width: 300,
          height: 120,
          child: ,
      )
    )
 */

/// 绘制竖直虚线
class CNMDottedLinePainer extends CustomPainter {
  /// 画布的颜色
  final Color rectBgColor;

  /// 虚线的颜色
  final Color paintColor;

  /// 虚线的宽度
  final double dottedLineW;

  /// 虚线之间的间距
  final double dottedVerMargin;

  /// 水平、垂直偏移量
  final Offset offset;

  // 创建画布
  final Paint _bgPaint;
  // 创建每个点
  final Paint _pointPaint;

  CNMDottedLinePainer({
    this.rectBgColor = Colors.white,
    this.paintColor = const Color(0xffcccccc),
    this.dottedLineW = 3,
    this.dottedVerMargin = 8,
    this.offset = Offset.zero,
  })  : _bgPaint = Paint()..color = rectBgColor,
        _pointPaint = Paint()
          ..color = paintColor
          ..strokeCap = StrokeCap.round
          ..strokeWidth = dottedLineW;

  @override
  void paint(Canvas canvas, Size size) {
    // 绘制画布
    canvas.drawRect(Offset.zero & size, _bgPaint);

    // 初始化第一个标的坐标
    List<Offset> offsets = [offset];

    int number = (size.height / dottedVerMargin).round();

    for (var i = 0; i < number; i++) {
      offsets.add(Offset(offset.dx, offset.dy + i * dottedVerMargin));
    }

    canvas.drawPoints(PointMode.points, offsets, _pointPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
